package com.ibm.iisp.common.web.springmvc.view;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.servlet.view.AbstractUrlBasedView;

public class ClasspathResourceView extends AbstractUrlBasedView {
	Logger log = LoggerFactory.getLogger(getClass());
	private String prefix;
	@Override
	protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ServletOutputStream outstrm = response.getOutputStream();
		String path = prefix + request.getRequestURI();
		ClassPathResource classPathResource = new ClassPathResource(path);
		BufferedInputStream bis = new BufferedInputStream(classPathResource.getInputStream());
		
        byte[] contents = new byte[1024];  
        int byteRead = 0;  
        try {  
            while((byteRead = bis.read(contents)) != -1){
            	outstrm.write(contents, 0, byteRead);
            }  
        } catch (IOException e) {  
            log.error("Erro to write resource: classpath:" + path, e);  
        } finally {
        	bis.close();  
        	outstrm.flush();
        }
		
	}
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

}
